package queue;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;

public class BlockingClient implements QueueFactory {

	private final Socket socket;
	
	//@Property
	private int port;
	public BlockingClient setPort(int port)
		{ this.port = port; return this; }
	
	//@Property
	private String hostname;
	public BlockingClient setHostname(String hostname)
		{ this.hostname = hostname; return this; }
	
	public BlockingClient() {
		socket = new Socket();
	}
	
	public void stop() {
		try {
			socket.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void start() {
		try {
			socket.connect(new InetSocketAddress(hostname, port));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public Queue getQueue() {
		return new Queue() {
			public void put(Message message) {
				try {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] len = new byte[CodedOutputStream.computeRawVarint32Size(message.getSerializedSize())];
					CodedOutputStream.newInstance(len).writeRawVarint32(message.getSerializedSize());
					baos.write(len);
					baos.flush();
					baos.write(message.toByteArray());
					baos.flush();
					System.out.println(String.format("Client: %s", Arrays.toString(baos.toByteArray())));
					socket.getOutputStream().write(baos.toByteArray());
					socket.getOutputStream().flush();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}};
	}	
	
}
